package org.feichao.wordinspector.ui;

import com.aspose.words.Document;
import com.aspose.words.ImportFormatMode;
import com.aspose.words.NodeImporter;
import com.aspose.words.NodeType;
import com.aspose.words.Paragraph;
import com.aspose.words.SaveFormat;
import com.aspose.words.SaveOptions;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.io.File;
import java.util.UUID;
import java.util.logging.Level;
import javax.swing.JEditorPane;
import org.feichao.wordinspector.Application;
import org.feichao.wordinspector.beans.DocumentNode;
import org.feichao.wordinspector.util.Logger;
import org.xhtmlrenderer.context.AWTFontResolver;
import org.xhtmlrenderer.simple.XHTMLPanel;

/**
 *
 * @author chao
 * @since 2015-4-27
 */
public class ContentPanel extends /*XHTMLPanel*/ JEditorPane{

    DocumentNode node;

    public ContentPanel() {
        setContentType("text/html");
        setEditable(false);

//        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
//        Font[] fonts = ge.getAllFonts();
//        AWTFontResolver resolver = (AWTFontResolver) getSharedContext().getFontResolver();
//        for(Font font: fonts){
//            resolver.setFontMapping(font.getFontName(), font);
//            Logger.info("Family[%s] name[%s]", font.getFamily(),font.getFontName());
//        }

    }


    public void setDocumentNode(DocumentNode node){
        this.node = node;
        update();
    }
    
    public void update(){
        try {
            //产生新的文档，然后将需要展示的节点粘贴进去，并生成HTML用于展示
            Document newDocument = new Document();
            NodeImporter importer = new NodeImporter(node.node.getDocument(), newDocument, ImportFormatMode.KEEP_SOURCE_FORMATTING);
            if(node.node.getNodeType() == NodeType.SECTION){
                newDocument.appendChild(importer.importNode(node.node, true));
            }else if(node.node.getNodeType() == NodeType.PARAGRAPH){
                newDocument.getFirstSection().getBody().appendChild(importer.importNode(node.node, true));
            }else{
                Paragraph p = new Paragraph(newDocument);
                p.appendChild(importer.importNode(node.node, true));
                newDocument.getFirstSection().getBody().appendChild(p);
            }
            File tmpDir = Application.getTmpDir();
            tmpDir.mkdirs();
            File htmlFile = new File(tmpDir, UUID.randomUUID().toString() + ".html");
            newDocument.save(htmlFile.getAbsolutePath(), SaveOptions.createSaveOptions(SaveFormat.HTML));

            setPage(htmlFile.toURI().toURL());
//            setDocument(htmlFile);
        } catch (Exception ex) {
            Logger.error(ex, "Error in previewing");
        }
    }


    

}
